$(document).ready(function() {
    // 导入本地存储模块
    const storage = require("./modules/storage.js");

    // 声明变量
    const form = {
        useType: "STD",
        factoryArea: "ALL",
        processType: "BGBL",
        needInvoice: false,
        count: "",
        expectedMinPrice: "",
        expectedDeliveryTime: "",
        contactName: "",
        remarks: "",
        catId: "",
        material: "",
        styleId: "",
        styleImg: ""
    };

    // 导入上传文件模块
    const upload = require("./modules/upload.js");

    // 导入api模块
    const api = require("./modules/api.js");
    let catList = [];
    let materials = [];
    let subcats = [];
    let styles = [];
    let subCatId = "";

    // 获取材质
    storage.getCats().then(res => {
        console.log("-------res-------");
        console.log(res);
        catList = res;
        console.log(catList);
        catList[0].material.split(",").map(item => {
            if (item) {
                materials.push(item);
            }
        });

        // 选取第一个地默认
        form.material = materials[0];
        form.catId = catList[0].id;
        $("#process-cat").text(catList[0].name);

        render_material();
        render_cat();
        handle_select_cat();
        getStyles();
    });


    // 选择类目
    function handle_select_cat() {
        $(".cats-content .cats .cat-item").each(function(index) {
            $(this).click(function(e) {
                e.stopPropagation();

                $(".cats-content .cats .cat-item").removeClass("cat-active");
                $(this).addClass("cat-active");
                if ((form.catId == catList[index].id) && ($(".sub-cats")[0].style.display == "block")) {
                    console.log("good");
                    $(".sub-cats").hide();
                } else {
                    $(".sub-cats").show();
                };

                // 获取当前的材质
                materials = catList[index].material.split(",");


                form.material = materials[0];
                form.catId = catList[index].id;
                $("#process-cat").text(catList[index].name);
                

                // 获取样式
                getStyles();

                // 获取当前类目的下级类目
                subcats = catList[index].subCats;

                console.log("form.catId: ", form.catId);
                console.log("form.material: ", form.material);

                // 渲染材质
                render_material();

                // 渲染下级类目
                render_subcat(index);
                handle_select_subcat();
            });
        });
    };
    
    // 关闭类目
    $("body").click(function(){
        $(".sub-cats").hide();
    });

    // 选择下级类目
    function handle_select_subcat() {
        $(".sub-cats .sub-cats-content .sub-cats-item").each(function(index) {
            $(this).click(function() {
                form.catId = subcats[index].id;
                subCatId = subcats[index].id;
                $("#process-cat").text(subcats[index].name);

                // 获取当前材质
                if (subcats[index].material) {
                    materials = subcats[index].material.split(",");
                    form.material = materials[0];
                    console.log("---material-----");
                    console.log(materials);

                    // 渲染材质
                    render_material();
                };
                // 获取样式
                getStyles();
                $(".sub-cats").hide();
            });
        });
    };

    // 渲染材质
    function render_material() {
        // 渲染材质时，默认选中第一个
        let html = "";
        for (let i = 0; i < materials.length; i++) {
            if (form.material && form.material == materials[i]) {
                html += `<div class="caizhi-item caizhi-item-active">${materials[i]}</div>`;
            } else {
                html += `<div class="caizhi-item">${materials[i]}</div>`;
            };
        };
        $(".caizhis").empty();
        $(".caizhis").append(html);
        handle_select_material();
    };

    // 选择材质
    function handle_select_material() {
        $(".caizhis .caizhi-item").each(function(index) {
            $(this).click(function() {
                form.material = materials[index];
                console.log(form.material);
                // 关闭下级类目
                $(".sub-cats").hide();
                // 获取样式
                getStyles();
                $(".caizhis .caizhi-item").removeClass("caizhi-item-active").eq(index).addClass("caizhi-item-active");
            });
        });
    };


    // 渲染分类
    function render_cat() {
        let html = "";
        for (let i = 0; i < catList.length; i++) {
            if (form.catId && form.catId == catList[i].id) {
                html += `<div class="cat-item cat-active">
                        <img class="cat-logo" src="${catList[i].image}">
                        <p class="cat-title">${catList[i].name}</p>
                        <div class="cat-border"></div>
                    </div>`;
            } else {
                html += `<div class="cat-item">
                        <img class="cat-logo" src="${catList[i].image}">
                        <p class="cat-title">${catList[i].name}</p>
                        <div class="cat-border"></div>
                    </div>`;
            }

        };
        $(".cats").empty();
        $(".cats").append(html);
    };

    // 渲染下级分类
    function render_subcat(i) {
        let html = "";
        console.log("catId: ", form.catId);

        for (let i = 0; i < subcats.length; i++) {
            if (subCatId && subCatId == subcats[i].id) {
                html += `<div class="sub-cats-item sub-cats-item-active">${subcats[i].name}</div>`;
            } else {
                html += `<div class="sub-cats-item">${subcats[i].name}</div>`;
            };

        };
        console.log("i: ", i);
        $(".sub-cats-content").empty().append(html);
        

        let parentCat = $(".cats .cat-item").eq(i);
        let top = parentCat.position().top;
        console.log(top);
        
        
        //let left = ( (i + 1 ) % 7 - 1) * 129 + "px";
        
        let left = (i % 6)  * 129 + "px";
        console.log("left: ", left);
        if( i % 6 < 3){
            console.log("bad");
            $(".sub-cats").css({top: top + 127 + "px", left: left});
        }else{
            console.log("----ok---");
            $(".sub-cats").css({top: top + 127 + "px", left: "auto" , right: "0px"});
        };
        

    };
    // 获取样式
    function getStyles() {
        let catId = form.catId;
        api.process_styleList({
            catId: form.catId,
            material: form.material
        }).then(res => {
            console.log(res);
            styles = res.result.list || [];
            if (styles.length == 0) {
                $(".kuanshi-container").hide();
                $(".no").show();
            } else {
                $(".kuanshi-container").show();
                $(".no").hide();
                render_style();
            }

        });
    };

    // 渲染样式
    function render_style() {
        console.log("------styles-------");
        console.log(styles);
        let html = "";
        styles.map(item => {
            html += `
					<div class="kuanshi-item">
                        <img class="kuanshi-logo" src="${item.cover.split(",")[0]}">
                        <div class="kuanshi-selected"></div>
                        <p class="kuanshi-no">编号：0192928</p>
                        <p class="kuanshi-tedian">特点：肩宽，肩宽</p>
                    </div>
				`;
        });

        $(".kuanshi-container .kuanshis").empty().append(html);
        style_carousel();
        select_style();
    };

    // 样式轮播
    function style_carousel() {
        let styles_length = styles.length;

        let i = 0;
        $(".kuanshi-container .btn-next").addClass("btn-active");

        if (styles_length > 4) {
            $(".kuanshi-container .btn").show();
        } else {
            $(".kuanshi-container .btn").hide();
        };

        $(".kuanshi-container .btn-prev").click(function() {
            if (i > 0) {
                i -= 1;
                console.log(i);
                move();

            }
        });


        $(".kuanshi-container .btn-next").click(function() {
            if (i < styles_length - 4) {
                i += 1;
                console.log(i);
                move();
            };
        });

        function move() {
            let left = -i * 200 + "px";
            $(".kuanshi-container .kuanshis").animate({ left: left });
            if (i > 0) {
                $(".kuanshi-container .btn-prev").addClass("btn-active");
            } else {
                $(".kuanshi-container .btn-prev").removeClass("btn-active");
            };
            if (i == styles_length - 4) {
                $(".kuanshi-container .btn-next").removeClass("btn-active");
            } else {
                $(".kuanshi-container .btn-next").addClass("btn-active");
            };
        };
    };

    // 选择样式
    function select_style() {
        $(".kuanshis .kuanshi-item").each(function(index) {
            $(this).click(function() {
                console.log(index);
                form.styleId = styles[index].id;
                $(".kuanshis .kuanshi-item").find(".kuanshi-selected").fadeOut();
                $(this).find(".kuanshi-selected").fadeIn();
            });
        });
    };


    function expectedDeliveryTime_validator() {
        var val = $("#expectedDeliveryTime").val();
        // if (!val) {
        //     $("#expectedDeliveryTime").nextAll(".error-message").text("请填写交货期！").fadeIn();
        //     return false;
        // };
        // 获取选择的日期
        var selectDate = new Date(val + " 23:59:59");
        // 获取选择的时间戳
        var selectDateTimestamp = selectDate.getTime();

        // 获取当前日期
        var nowDateTimestamp = new Date().getTime();

        if (selectDateTimestamp < nowDateTimestamp) {
            $("#expectedDeliveryTime").nextAll(".error-message").text("期望交货期时间不能在今天之前！").fadeIn();
            return false;
        };


        $("#expectedDeliveryTime").nextAll(".error-message").fadeOut();
        form.expectedDeliveryTime = val;
        return true;
    };

    //选择用途
    $(".useType").click(function() {
        $(".useType").removeClass("yongtu-active");
        $(this).addClass("yongtu-active");
        form.useType = $(this).data().val;

        if(form.useType == "STD"){
            $("#process-use").text("实体店");
        }else if(form.useType == "TM"){
            $("#process-use").text("天猫点");
        }else if(form.useType == "TB"){
            $("#process-use").text("淘宝点");
        }else if(form.useType == "WS"){
            $("#process-use").text("微商点");
        };
    });

    //选择区域
    $(".factoryArea").click(function() {
        $(".factoryArea").removeClass("quyu-active");
        $(this).addClass("quyu-active");
        form.factoryArea = $(this).data().val;

        if(form.factoryArea == "ALL"){
            $("#process-area").text("全国");
        }else if(form.factoryArea == "JZH"){
            $("#process-area").text("江浙沪");
        }else if(form.factoryArea == "GD"){
            $("#process-area").text("广东");
        };
    });

    //选择加工类型
    $(".processType").click(function() {
        $(".processType").removeClass("jiagong-item-active");
        $(this).addClass("jiagong-item-active");
        form.processType = $(this).data().val;
        if(form.processType == "BGBL"){
            $("#process-type").text("包工包料");
        }else if(form.processType == "QJG"){
            $("#process-type").text("轻加工");
        };
    });

    //是否需要发票
    $(".needInvoice").click(function() {
        $(".needInvoice").removeClass("fapiao-item-active");
        $(this).addClass("fapiao-item-active");
        form.needInvoice = $(this).data().val;
        if(form.needInvoice == true){
            console.log("goood");
            $("#process-fapiao").text("不要发票");
        }else if(form.needInvoice == false){
            console.log("bade");
            $("#process-fapiao").text("需要发票");
        };
    });

    //监测数量输入
    $("#count").bind("input property", function() {
        if(count_validator()){
            $("#process-quantity").text(form.count);
        };
    });

    function count_validator() {
        let count = $("#count").val();
        if (!count) {
            $("#count").nextAll(".error-message").text("请填写加工数量!").fadeIn();
            return false;
        };
        if (isNaN(count)) {
            $("#count").nextAll(".error-message").text("请填写整数!").fadeIn();
            return false;
        };
        form.count = count;
        $("#count").nextAll(".error-message").fadeOut();
        return true;
    };

    //监测期望值最低价
    $("#expectedMinPrice").bind("input property", function() {
        if(expectedPrice_validator()){
            let min = $("#expectedMinPrice").val();
            let max = $("#expectedMaxPrice").val();
            let fanwei = `${min}元 ~ ${max}元`;
            $("#process-fanwei").text(fanwei);
        }else{
            $("#process-fanwei").text("暂无");
        };
    });
    //监测期望值最高价
    $("#expectedMaxPrice").bind("input property", function() {
        if(expectedPrice_validator()){
            let min = $("#expectedMinPrice").val();
            let max = $("#expectedMaxPrice").val();
            let fanwei = `${min}元 ~ ${max}元`;
            $("#process-fanwei").text(fanwei);
        }else{
            $("#process-fanwei").text("暂无");
        };
    });

    function expectedPrice_validator() {
        let expectedMinPrice = $("#expectedMinPrice").val();
        let expectedMaxPrice = $("#expectedMaxPrice").val();
        // if (!expectedMinPrice) {
        //     $("#expectedMinPrice").nextAll(".error-message").text("请填写期望值最低价!").fadeIn();
        //     return false;
        // };
        if (expectedMinPrice && isNaN(expectedMinPrice)) {
            $("#expectedMinPrice").nextAll(".error-message").text("请填写数字！").fadeIn();
            return false;
        };
        // if (!expectedMaxPrice) {
        //     $("#expectedMaxPrice").nextAll(".error-message").text("请填写期望值最高价!").fadeIn();
        //     return false;
        // };
        if (expectedMaxPrice && isNaN(expectedMaxPrice)) {
            $("#expectedMaxPrice").nextAll(".error-message").text("请填写数字！").fadeIn();
            return false;
        };
        if (expectedMinPrice && expectedMinPrice && (expectedMinPrice > expectedMaxPrice)) {
            $("#expectedMaxPrice").nextAll(".error-message").text("期望值最高价不能低于期望值最低价！").fadeIn();
            return false;
        };

        form.expectedMinPrice = expectedMinPrice;
        form.expectedMaxPrice = expectedMaxPrice;

        $("#expectedMinPrice").nextAll(".error-message").fadeOut();
        return true;
    };


    //监测联系姓名
    $("#contactName").bind("input property", function() {
        if(contactName_validator()){
            $("#process-username").text(form.contactName);
        };
    });

    function contactName_validator() {
        let contactName = $("#contactName").val();
        // if (!contactName) {
        //     $("#contactName").nextAll(".error-message").text("请填写姓名！").css({ "display": "block", "margin-left": "0", "margin-top": "10px" }).fadeIn();
        //     return false;
        // };
        form.contactName = contactName;
        //$("#contactName").nextAll(".error-message").fadeOut();
        return true;
    };

    //监测手机号变化
    $("#contactPhone").bind("input property", function() {
        if(contactPhone_validator()){
            $("#process-phone").text(form.contactPhone);
        };
    });

    function contactPhone_validator() {
        let contactPhone = $("#contactPhone").val();
        // if (!contactPhone) {
        //     $("#contactPhone").nextAll(".error-message").text("请填写手机号！").css({ "display": "block", "margin-left": "0", "margin-top": "10px" }).fadeIn();
        //     return false;
        // };
        if (contactPhone && !/^[1][3,4,5,7,8][0-9]{9}$/.test(contactPhone)) {
            $("#contactPhone").nextAll(".error-message").text("请填写合法手机号！").css({ "display": "block", "margin-left": "0", "margin-top": "10px" }).fadeIn();
            return false;
        };
        form.contactPhone = contactPhone;
        $("#contactPhone").nextAll(".error-message").fadeOut();
        return true;
    };

    // 监测备注
    $("#remarks").bind("input property", function() {
        let remarks = $("#remarks").val();
        form.remarks = remarks;
    });

    // 点击提交
    $("#submit").click(function() {
        console.log(form);
        if (on_submit_validator()) {
        	console.log("提交");
            api.process_demand(form).then(res => {
            	console.log(res);
                if (res.code == "0") {
                    window.location.href = "/success";
                };
                console.log(res);
            });
        }

    });
    

    let datePicker = new DatePicker({
        element: "#expectedDeliveryTime",
        onSelected: function() {
            if(expectedDeliveryTime_validator()){
                $("#process-jiaohuoqi").text(form.expectedDeliveryTime);
            };
        }
    });
    datePicker.init();

    // 展开
    $("#additional-btn").click(function() {
        if ($(".additional").css("display") == "block") {
            $(".additional").slideUp(200);
            $(this).css({ "background-image": "url(/img/down_logo.png)" });
            // 导入datePicker组件
		    
        } else {
        	
            $(".additional").slideDown(200);
            $(this).css({ "background-image": "url(/img/up_icon.png)" });
        };
    });

    function on_submit_validator() {
        return [
            count_validator(),
            contactName_validator(),
            contactPhone_validator(),
            expectedPrice_validator(),
            expectedDeliveryTime_validator()
        ].every((item) => item);
    };

    // 上传文件
    $("#file").change(function(){
        console.log("good");
        upload("#file", (res)=>{
            console.log(res);
            if(res.code == "0"){
                $("#upload-img").attr("src", res.result.img_url);
                $(".empty-container").hide();
                $(".img-container").show();
                form.styleImg = res.result.img_url;
            }
        });
    });
    // 删除图片
    $(".remove-icon").click(function(){
        $(".empty-container").show();
        $(".img-container").hide();
        $("#file").val("");
        form.styleImg = "";
    });
});